<template>
    <div class="content" ref="contentRef">
        <el-form
            ref="queryFormRef"
            :model="queryForms"
            label-width="10rem"
            label-position="left"
            :rules="queryFormRules"
        >
            <el-row :gutter="24">
                <el-col :span="12">
                    <el-form-item label="发生地点：" required prop="place">
                        <el-input v-model="queryForms.place"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="发生时间：" required prop="occurdate">
                        <el-date-picker
                            v-model="queryForms.occurdate"
                            type="datetime"
                            placeholder="请选择发生时间"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="预案名称：" required prop="planId">
                        <PlanNameSelect v-model="queryForms.planId" @change="generateDisposalPlanHandle"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="重点对象：" required prop="peopleId">
                        <KeyPersonManageSelect v-model="queryForms.peopleId"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="性别：">
                        <el-radio-group v-model="queryForms.sex" @change="generateMeasureHandle">
                            <el-radio-button
                                v-for="item in sys_user_sex"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="是否携带未成年人：">
                        <el-radio-group v-model="queryForms.isYet" @change="generateMeasureHandle">
                            <el-radio-button
                                v-for="item in sys_yes_no"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="是否年龄大于70周岁：">
                        <el-radio-group v-model="queryForms.isSeventy" @change="generateMeasureHandle">
                            <el-radio-button
                                v-for="item in sys_yes_no"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="是否为残障人士：">
                        <el-radio-group v-model="queryForms.isDisabled" @change="generateMeasureHandle">
                            <el-radio-button
                                v-for="item in sys_yes_no"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-radio-group>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <el-form
            :model="queryForms"
            label-width="auto"
        >
            <el-form-item label="是否为醉酒、精神障碍患者且不能正确表达自己意志：">
                <el-radio-group v-model="queryForms.isDrunken" @change="generateMeasureHandle">
                    <el-radio-button
                        v-for="item in sys_yes_no"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-radio-group>
            </el-form-item>

        </el-form>

        <el-form
            :model="queryForms"
            label-width="auto"
        >
            <el-form-item label="已采取的措施和应对：" label-position="top">
                <el-input v-model="queryForms.measure" type="textarea" :rows="3" disabled/>
            </el-form-item>
            <el-form-item label="事件性质：" label-position="top">
                <el-select
                    v-model="queryForms.nature"
                    placeholder="请选择事件性质"
                >
                    <el-option
                        v-for="item in nj_event_nature"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item v-for="(item, index) in textAreas" :key="index" :label="item.label" label-position="top">
                <el-input v-model="queryForms[item.model]" type="textarea" :rows="3"/>
            </el-form-item>
        </el-form>

        <div class="footer">
            <!-- 创建 -->
            <el-button type="primary" @click="createHandle(queryFormRef)" v-if="!isEdit">提交</el-button>
            <!-- 更新 -->
            <el-button type="primary" @click="updateHandle" v-else>提交</el-button>
            <!-- 取消 -->
            <el-button @click="closeDrawerHandle">关闭</el-button>
        </div>
    </div>
</template>

<script setup>
import KeyPersonManageSelect from "@/components/KeyPersonManageSelect/KeyPersonManageSelect.vue";
import PlanNameSelect from "@/components/PlanNameSelect/PlanNameSelect.vue";
import {ElMessage} from "element-plus";
import {getPlanInfo} from "@/api/PlanManage/Plan.js";
import {addEmergencyAction, getEmergencyActionInfo, updateEmergencyAction} from "@/api/FireAction/ExecuteFireAction.js";
import {getCurrentTime} from "@/utils/utils.js";
import {useTemplateRef} from "vue";

const {onCloseDrawer, warningData} = defineProps(['onCloseDrawer', 'warningData'])

const emit = defineEmits(['close'])

const isEdit = inject('isEdit', false)
const managementId = inject('managementId', '')

const {proxy} = getCurrentInstance()
const {
    sys_yes_no, nj_event_nature, sys_user_sex
} = proxy.useDict('sys_yes_no', 'nj_event_nature', 'sys_user_sex')

// 已采取的措施和应对固定内容
const defaultMeasureList = {
    // 预案名称
    planMeasure: '',
    // 性别
    sex: '',
    // 是否携带未成年人
    yet: '',
    // 为残障人士的内容
    disabled: '',
    // 年龄大于70周岁的内容
    seventy: '',
    // 为醉酒、精神障碍患者且不能正确表达自己意志的内容
    drunken: ''
}
const measureList = ref({...defaultMeasureList})

const defaultQueryForm = {
    // 发生地点
    place: '',
    // 预案名称
    planId: '',
    // 发生时间
    occurdate: '',
    // 重点对象
    peopleId: '',
    // 性别
    sex: '1',
    // 是否携带未成年人
    isYet: '2',
    // 是否为残障人士
    isDisabled: '2',
    // 是否年龄大于70周岁
    isSeventy: '2',
    // 是否为醉酒、精神障碍患者且不能正确表达自己意志
    isDrunken: '2',
    // 已采取的措施和应对
    measure: '',
    // 事件性质
    nature: '',
    // 涉及人员及规模
    scope: '',
    // 破坏程度及人员伤亡情况
    damage: '',
    // 发生的起因
    cause: '',
    // 影响程度评估
    influence: '',

    adddate: '',
    updatedate: '',
}
const queryForms = ref({...defaultQueryForm})

// 应急预警来的数据
const emergencyWarningData = ref({})

const textAreas = [
    {label: "涉及人员及规模：", model: "scope"},
    {label: "破坏程度及人员伤亡情况：", model: "damage"},
    {label: "发生的起因：", model: "cause"},
    {label: "影响程度评估：", model: "influence"},
]

const queryFormRef = useTemplateRef('queryFormRef')
const queryFormRules = reactive({
    place: [
        {required: true, message: '请输入发生地点', trigger: 'blur'}
    ],
    occurdate: [
        {required: true, message: '请选择发生时间', trigger: 'blur'}
    ],
    planId: [
        {required: true, message: '请选择预案名称', trigger: 'blur'}
    ],
    peopleId: [
        {required: true, message: '请选择重点对象', trigger: 'blur'}
    ],
})
// ===========================================================================================

onMounted(() => {
    if (isEdit.value) {
        getExecuteFireActionDetailHandle()
    }
    // console.log('isEdit', isEdit.value)
})

// 使用 watch 监听 warningData 的变化
watch(() => warningData, (newValue, oldValue) => {
    // 当 warningData 发生变化时，执行这里的代码
    // console.log('warningData changed:', JSON.stringify(newValue), oldValue);
    queryForms.value = {
        ...queryForms.value,
        // 预警 ID
        warningId: newValue.warningId ?? "",
        // 发生地点
        place: newValue.place ?? "",
        // 发生时间
        occurdate: newValue.warningdate ?? "",
        // // 性别
        sex: newValue.sex ?? "1",
        // 重点对象
        peopleId: newValue.peopleId ?? ""
    }
    // 这里可以执行一些基于 newValue 的逻辑
}, {
    deep: true, // 如果 warningData 是一个对象或数组，你可能需要开启深度监听
    immediate: true // 是否在组件挂载时立即执行一次监听器的回调函数
});


// 生成采取措施跟应对内容
const generateMeasureHandle = () => {
    measureList.value.sex = queryForms.value.sex === '2' ? '对女性信访人员的人身安全检查，应由女司法警察或女检察人员进行。' : ''
    measureList.value.drunken = queryForms.value.isDrunken === '1' ? '拒绝让其进入信访接待场所。' : ''
    measureList.value.disabled = queryForms.value.isDisabled === '1' ? '提供必要帮助、允许携带拐杖等辅助器材。' : ''
    measureList.value.seventy = queryForms.value.isSeventy === '1' ? '提供必要帮助。' : ''
    measureList.value.yet = queryForms.value.isYet === '1' ? '禁止采用过激的控制方式。' : ''

    // console.log('measureList 内容：', JSON.stringify(measureList.value))
    const content = Object.keys(measureList.value).map(item => measureList.value[item]).filter(item => item.length > 0)
    // console.log(content)
    queryForms.value.measure = content.join('\n')
}

// 生成处置方案
const generateDisposalPlanHandle = async () => {
    if (queryForms.value.planId.length <= 0) {
        ElMessage.error('请选择预案名称')
        return ''
    }

    const res = await getPlanInfo(queryForms.value.planId)
    measureList.value.planMeasure = res.data.measure
    // console.log(res)
    generateMeasureHandle()
}

// 获取应急处置详情
const getExecuteFireActionDetailHandle = async () => {
    const res = await getEmergencyActionInfo(managementId.value)
    // console.log('应急处置详情', res)
    queryForms.value = {
        ...queryForms.value,
        ...res.data
    }
    // console.log(JSON.stringify(queryForms.value))
}

// 创建应急处置
const createHandle = async (elForm) => {
    if (!elForm) return
    await elForm.validate(async (valid, fields) => {
        if (valid) {
            const time = getCurrentTime()
            queryForms.value.adddate = time
            queryForms.value.updatedate = time
            await addEmergencyAction(queryForms.value)
            emit('close')
            console.log('提交内容', JSON.stringify(queryForms.value))
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 更新应急处理
const updateHandle = async () => {
    // console.log(JSON.stringify(queryForms.value))
    await updateEmergencyAction(queryForms.value)
    emit('close')
}

// 取消事件
const closeDrawerHandle = () => {
    measureList.value = {...defaultMeasureList}
    queryForms.value = {...defaultQueryForm}
    onCloseDrawer()
}
</script>

<style scoped lang="scss">

.content {
    padding-bottom: 5.625rem;

    .footer {
        position: fixed;
        bottom: 30px;
        right: 0;
        width: 50%;
        background-color: #fff;
        padding: var(--el-drawer-padding-primary);
        text-align: right;
        border-top: 0.0625rem solid var(--el-color-info-light-9);
    }
}
</style>